<template lang="pug">
  div.previjw(v-show="preview")
    div.svg-wrapper(v-html="preview" :style="{backgroundColor}")
    span.note {{ format.name }}
</template>

<script setup>

import { computed, ref, onMounted, watch, inject, nextTick } from 'vue';
import { mergeFormatSvg, TEMPLATE } from '../../utils/meregeFormatSvg.util'
import * as mockData from './mockData.js'

const props = defineProps({
  format: { type: Object },
})
const mainBrandId = inject('mainBrandId')
const colors = inject('colors')
const graphics = inject('graphics')
const compositions = inject('compositions')
const schemes = inject('schemes')
const suites = inject('suites')


const preview = ref('')

watch(() => props.format, format => {
  if (!checkElements(format.elements)) { return }
  if (!format.suite) {
    const suite = suites.value.find(s => s.id === format?.suiteId)
    if (!suite) { return }
    format.suite = suite
  }
  const resource = {
    colors: colors.value,
    graphics: graphics.value,
    compositions: compositions.value,
    schemes: schemes.value,
    suites: suites.value,
  }
  nextTick(() => {
    const svg = mergeFormatSvg(format, resource)
    // const svg = mergeFormatSvg(format, { ...mockData })
    preview.value = svg
  })
}, { deep: true, immediate: true })

function checkElements(elements) {
  let isKeyCompleted = true
  for (let i = 0; i < elements.length; i++) {
    const keys = Object.keys(elements[i])
    const sizes = ['height', 'width'];
    const horizontals = ['left', 'center', 'right'];
    const verticals = ['top', 'center', 'bottom'];
    const hasSize = keys.some(item => sizes.includes(item));
    const hasHorizontal = keys.some(item => horizontals.includes(item));
    const hasVertical = keys.some(item => verticals.includes(item));
    isKeyCompleted = isKeyCompleted && hasSize && hasHorizontal && hasVertical
  }
  return isKeyCompleted
}

const backgroundColor = computed(() => {
  const colorId = props.format.backgroundColorId
  const color = colors.value.find(c => c.id == colorId)
  return color?.hex
})

</script>

<style scoped>
.note {
  font-size: 0.7rem;
}

.svg-wrapper svg {
  border: 2px solid #fff;
}
</style>
